<template>
  <div class="doctor-schedule">
    <div class="page-header">
      <h2>{{ currentUser }}医生</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateSchedule">
          <el-icon><Plus /></el-icon>
          申请调班
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 排班概览 -->
    <div class="schedule-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-item">
              <div class="overview-icon today-shifts">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="overview-content">
                <div class="overview-value">{{ overview.todayShifts }}</div>
                <div class="overview-label">今日班次</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-item">
              <div class="overview-icon week-shifts">
                <el-icon><List /></el-icon>
              </div>
              <div class="overview-content">
                <div class="overview-value">{{ overview.weekShifts }}</div>
                <div class="overview-label">本周班次</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-item">
              <div class="overview-icon pending-requests">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="overview-content">
                <div class="overview-value">{{ overview.pendingRequests }}</div>
                <div class="overview-label">待处理申请</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-item">
              <div class="overview-icon total-hours">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="overview-content">
                <div class="overview-value">{{ overview.totalHours }}h</div>
                <div class="overview-label">本月工作时长</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 排班日历 -->
    <el-card class="schedule-calendar-card">
      <template #header>
        <div class="calendar-header">
          <div class="calendar-nav">
            <el-button @click="prevPeriod" text>
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <span class="current-period">{{ currentPeriod }}</span>
            <el-button @click="nextPeriod" text>
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
          <div class="calendar-actions">
            <el-button-group>
              <el-button
                :type="viewMode === 'month' ? 'primary' : ''"
                @click="switchViewMode('month')"
              >
                月视图
              </el-button>
              <el-button
                :type="viewMode === 'week' ? 'primary' : ''"
                @click="switchViewMode('week')"
              >
                周视图
              </el-button>
              <el-button
                :type="viewMode === 'day' ? 'primary' : ''"
                @click="switchViewMode('day')"
              >
                日视图
              </el-button>
            </el-button-group>
            <el-button @click="goToToday">
              <el-icon><Position /></el-icon>
              今天
            </el-button>
          </div>
        </div>
      </template>

      <!-- 月视图 -->
      <div v-if="viewMode === 'month'" class="month-view">
        <div class="calendar-weekdays">
          <div v-for="day in weekdays" :key="day" class="weekday-header">
            {{ day }}
          </div>
        </div>
        <div class="calendar-days">
          <div
            v-for="day in calendarDays"
            :key="day.date"
            class="calendar-day"
            :class="{
              'other-month': !day.isCurrentMonth,
              today: day.isToday,
              weekend: day.isWeekend,
            }"
          >
            <div class="day-header">
              <div class="day-number-wrapper">
                <span class="day-number">{{ day.day }}</span>
                <span v-if="day.isToday" class="today-badge">今</span>
              </div>
              <span class="lunar-date" v-if="day.lunarDate">{{
                day.lunarDate
              }}</span>
            </div>
            <div class="day-shifts">
              <div
                v-for="shift in day.shifts"
                :key="shift.instance_id"
                class="shift-item"
                :class="getShiftTypeClass(shift.schedule_type)"
                @click="handleViewShift(shift)"
              >
                <div class="shift-time">
                  {{ formatShiftTime(shift.time_slot_code) }}
                </div>
                <div class="shift-location">{{ shift.location }}</div>
                <el-tag
                  v-if="shift.status"
                  :type="getShiftStatusType(shift.status)"
                  size="small"
                >
                  {{ getShiftStatusText(shift.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 周视图 -->
      <div v-else-if="viewMode === 'week'" class="week-view">
        <div class="week-header">
          <div class="week-range">{{ currentWeekRange }}</div>
        </div>
        <div class="week-timeline">
          <div class="time-slots">
            <div v-for="hour in timeSlots" :key="hour" class="time-slot">
              {{ hour }}:00
            </div>
          </div>
          <div class="week-days">
            <div
              v-for="day in weekDays"
              :key="day.date"
              class="week-day"
              :class="{ today: day.isToday, weekend: day.isWeekend }"
            >
              <div class="day-header">
                <div class="day-name">{{ day.weekday }}</div>
                <div class="day-date-wrapper">
                  <span class="day-date">{{ day.date }}</span>
                  <span v-if="day.isToday" class="today-badge">今</span>
                </div>
              </div>
              <div class="day-timeline">
                <div
                  v-for="hour in timeSlots"
                  :key="hour"
                  class="timeline-slot"
                  @click="handleCreateShift(day.fullDate, hour)"
                >
                  <div
                    v-for="shift in getShiftsForHour(day.fullDate, hour)"
                    :key="shift.instance_id"
                    class="timeline-shift"
                    :class="getShiftTypeClass(shift.schedule_type)"
                    :style="getShiftStyle(shift)"
                    @click.stop="handleViewShift(shift)"
                  >
                    <div class="shift-info">
                      <div class="shift-time">
                        {{ formatShiftTime(shift.time_slot_code) }}
                      </div>
                      <div class="shift-location">{{ shift.location }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 日视图 -->
      <div v-else class="day-view">
        <div class="day-header">
          <div class="day-title">{{ currentDayTitle }}</div>
        </div>
        <div class="day-timeline">
          <div class="time-slots">
            <div v-for="hour in dayTimeSlots" :key="hour" class="time-slot">
              {{ hour }}:00
            </div>
          </div>
          <div class="day-schedule">
            <div
              v-for="hour in dayTimeSlots"
              :key="hour"
              class="timeline-slot"
              @click="handleCreateShift(currentDayDate, hour)"
            >
              <div
                v-for="shift in getShiftsForHour(currentDayDate, hour)"
                :key="shift.instance_id"
                class="timeline-shift"
                :class="getShiftTypeClass(shift.schedule_type)"
                :style="getShiftStyle(shift)"
                @click.stop="handleViewShift(shift)"
              >
                <div class="shift-info">
                  <div class="shift-time">
                    {{ formatShiftTime(shift.time_slot_code) }}
                  </div>
                  <div class="shift-location">{{ shift.location }}</div>
                  <div class="shift-type">
                    {{ getScheduleTypeLabel(shift.schedule_type) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 近期排班 -->
    <el-card class="recent-schedule-card">
      <template #header>
        <div class="card-header">
          <span>近期排班</span>
        </div>
      </template>

      <el-table :data="recentSchedules" style="width: 100%" v-loading="loading">
        <el-table-column prop="schedule_date" label="日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.schedule_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="weekday" label="星期" width="80" />
        <el-table-column prop="time_slot_code" label="时间" width="150">
          <template #default="{ row }">
            {{ formatShiftTime(row.time_slot_code) }}
          </template>
        </el-table-column>
        <el-table-column prop="schedule_type" label="班次类型" width="100">
          <template #default="{ row }">
            <el-tag :class="getShiftTypeClass(row.schedule_type)" size="small">
              {{ getScheduleTypeLabel(row.schedule_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地点" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getShiftStatusType(row.status)" size="small">
              {{ getShiftStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleViewShift(row)">
              详情
            </el-button>
            <el-button
              v-if="row.status === 1"
              type="text"
              size="small"
              @click="handleRequestChange(row)"
            >
              申请调班
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 班次详情对话框 -->
    <el-dialog
      v-model="shiftDetailVisible"
      :title="selectedShift ? '班次详情' : '班次信息'"
      width="500px"
    >
      <ShiftDetail
        v-if="shiftDetailVisible"
        :shift-data="selectedShift"
        @request-change="handleRequestChangeFromDetail"
        @close="shiftDetailVisible = false"
      />
    </el-dialog>

    <!-- 调班申请对话框 -->
    <el-dialog v-model="changeRequestVisible" title="申请调班" width="600px">
      <ShiftChangeRequest
        v-if="changeRequestVisible"
        :shift-data="selectedShift"
        @submitted="handleChangeRequestSubmitted"
        @cancel="changeRequestVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import ShiftDetail from "@/components/doctor/ShiftDetail.vue";
import ShiftChangeRequest from "@/components/doctor/ShiftChangeRequest.vue";
// 引入后端API接口
import {
  getTimeSlotList,
  getScheduleTypeList,
  getDepartmentList,
} from "@/api/api";
import { queryDoctorScheduleInstanceData } from "@/api/doctor";

// 响应式数据
const viewMode = ref("month");
const currentDate = ref(new Date());
const shiftDetailVisible = ref(false);
const changeRequestVisible = ref(false);
const selectedShift = ref(null);
const loading = ref(false);
// vuex
const store = useStore();

// 排班时间和类型选项
const timeSlotOptions = ref([]);
const scheduleTypeOptions = ref([]);
// 科室数据
const departmentOptions = ref([]);
// 当前用户
const currentUser = computed(() => store.state.user?.doctor_name || {});

// 概览数据
const overview = reactive({
  todayShifts: 0,
  weekShifts: 0,
  pendingRequests: 0,
  totalHours: 0,
});

// 周历显示
const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
const timeSlots = Array.from({ length: 12 }, (_, i) => i + 8); // 8:00 - 19:00
const dayTimeSlots = Array.from({ length: 14 }, (_, i) => i + 7); // 7:00 - 20:00

// 计算属性
const currentMonth = computed(() => {
  return currentDate.value.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
  });
});

const currentPeriod = computed(() => {
  if (viewMode.value === "month") {
    return currentDate.value.toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "long",
    });
  } else if (viewMode.value === "week") {
    return currentWeekRange.value;
  } else {
    return currentDayTitle.value;
  }
});

const currentWeekRange = computed(() => {
  const start = new Date(currentDate.value);
  start.setDate(start.getDate() - start.getDay());
  const end = new Date(start);
  end.setDate(end.getDate() + 6);

  return `${formatSimpleDate(start)} - ${formatSimpleDate(end)}`;
});

const currentDayTitle = computed(() => {
  return currentDate.value.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    weekday: "long",
  });
});

const currentDayDate = computed(() => {
  return formatSimpleDate(currentDate.value);
});

const calendarDays = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();
  const today = new Date();

  // 当月第一天
  const firstDay = new Date(year, month, 1);
  // 当月最后一天
  const lastDay = new Date(year, month + 1, 0);
  // 日历开始日期（上周日）
  const startDate = new Date(firstDay);
  startDate.setDate(startDate.getDate() - startDate.getDay());
  // 日历结束日期（下周六）
  const endDate = new Date(lastDay);
  endDate.setDate(endDate.getDate() + (6 - lastDay.getDay()));

  const days = [];
  const current = new Date(startDate);

  while (current <= endDate) {
    const dateStr = formatSimpleDate(current);
    const shifts = scheduleData.value.filter(
      (shift) => shift.schedule_date === dateStr
    );

    days.push({
      date: dateStr,
      day: current.getDate(),
      isCurrentMonth: current.getMonth() === month,
      isToday: formatSimpleDate(current) === formatSimpleDate(today),
      isWeekend: current.getDay() === 0 || current.getDay() === 6,
      lunarDate: getLunarDate(current),
      shifts: shifts,
    });

    current.setDate(current.getDate() + 1);
  }

  return days;
});

const weekDays = computed(() => {
  const start = new Date(currentDate.value);
  start.setDate(start.getDate() - start.getDay());

  return Array.from({ length: 7 }, (_, i) => {
    const date = new Date(start);
    date.setDate(date.getDate() + i);
    const dateStr = formatSimpleDate(date);

    return {
      date: date.getDate(),
      weekday: weekdays[date.getDay()],
      fullDate: dateStr,
      isToday: formatSimpleDate(date) === formatSimpleDate(new Date()),
      isWeekend: date.getDay() === 0 || date.getDay() === 6,
    };
  });
});

// 排班数据
const scheduleData = ref([]);

const recentSchedules = computed(() => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 设置时间为当天开始

  // 过滤出今天及未来的排班，并按日期升序排序（今天→明天→后天...）
  return [...scheduleData.value]
    .filter((item) => {
      const itemDate = new Date(item.schedule_date);
      itemDate.setHours(0, 0, 0, 0);
      return itemDate >= today;
    })
    .sort((a, b) => new Date(a.schedule_date) - new Date(b.schedule_date)) // 升序排序
    .slice(0, 5) // 取前5条
    .map((item) => ({
      ...item,
      weekday: getWeekday(item.schedule_date),
    }));
});

// 方法
const prevPeriod = () => {
  const newDate = new Date(currentDate.value);
  if (viewMode.value === "month") {
    newDate.setMonth(newDate.getMonth() - 1);
  } else if (viewMode.value === "week") {
    newDate.setDate(newDate.getDate() - 7);
  } else {
    newDate.setDate(newDate.getDate() - 1);
  }
  currentDate.value = newDate;
};

const nextPeriod = () => {
  const newDate = new Date(currentDate.value);
  if (viewMode.value === "month") {
    newDate.setMonth(newDate.getMonth() + 1);
  } else if (viewMode.value === "week") {
    newDate.setDate(newDate.getDate() + 7);
  } else {
    newDate.setDate(newDate.getDate() + 1);
  }
  currentDate.value = newDate;
};

const switchViewMode = (mode) => {
  viewMode.value = mode;
  loadDoctorSchedule();
};

const goToToday = () => {
  currentDate.value = new Date();
};

const handleCreateSchedule = () => {
  // 设置一个默认的班次数据，或者传递当前选中的班次
  selectedShift.value = {
    date: new Date().toISOString().split('T')[0], // 默认今天
    time: '08:00-12:00',
    location: '门诊部',
    // 其他必要字段...
  };
  ElMessage.info("调班申请功能");
  changeRequestVisible.value = true;
};

const handleViewShift = (shift) => {
  // 关键修改：将数据库字段映射到 ShiftDetail 组件期望的字段
  const mappedShift = {
    // 基础信息
    id: shift.instance_id,
    date: shift.schedule_date,
    time: formatShiftTime(shift.time_slot_code),
    type: getScheduleTypeLabel(shift.schedule_type), // 映射类型
    location: shift.location,
    status: mapDbStatusToShiftStatus(shift.status), // 映射状态
    department: getDepartmentName(shift.department_id),

    // 工作统计
    maxPatients: shift.max_patients || 0,
    actualPatients: shift.actual_patients || 0,

    // 其他字段
    notes: `系统自动生成 - ${currentUser.value}的${getDepartmentName(
      shift.department_id
    )}排班 - ${getScheduleTypeLabel(shift.schedule_type)}班次`,

    // 保留原始数据用于其他操作
    _rawData: shift,
  };

  selectedShift.value = mappedShift;
  shiftDetailVisible.value = true;
};

const handleCreateShift = (date, hour) => {
  ElMessage.info(`在 ${date} ${hour}:00 创建班次`);
};

const handleRequestChange = (shift) => {
  selectedShift.value = shift;
  changeRequestVisible.value = true;
};

const handleRequestChangeFromDetail = (shift) => {
  shiftDetailVisible.value = false;
  selectedShift.value = shift;
  changeRequestVisible.value = true;
};

const handleChangeRequestSubmitted = () => {
  changeRequestVisible.value = false;
  ElMessage.success("调班申请已提交");
  loadDoctorSchedule(); // 重新加载数据
};

const refreshData = () => {
  loadDoctorSchedule();
  ElMessage.success("数据已刷新");
};

const getShiftsForHour = (date, hour) => {
  return scheduleData.value.filter((shift) => {
    if (shift.schedule_date !== date) return false;
    const timeSlot = timeSlotOptions.value.find(
      (t) => t.slot_code === shift.time_slot_code
    );
    if (!timeSlot) return false;
    const startHour = parseInt(timeSlot.start_time.split(":")[0]);
    return startHour === hour;
  });
};

const getShiftStyle = (shift) => {
  const timeSlot = timeSlotOptions.value.find(
    (t) => t.slot_code === shift.time_slot_code
  );
  if (!timeSlot) return { height: "60px" };

  const startHour = parseInt(timeSlot.start_time.split(":")[0]);
  const endHour = parseInt(timeSlot.end_time.split(":")[0]);
  const duration = endHour - startHour;

  return {
    height: `${duration * 60}px`,
  };
};

const getShiftTypeClass = (scheduleType) => {
  const classMap = {
    morning: "morning-shift",
    emergency: "emergency-shift",
    overtime: "night-shift",
    rest: "afternoon-shift",
    morning: "morning-shift",
    afternoon: "afternoon-shift",
    night: "night-shift",
    full_day: "morning-shift", // 全天班使用上午班样式
  };
  return classMap[scheduleType] || "default-shift";
};

const getScheduleTypeLabel = (scheduleType) => {
  const option = scheduleTypeOptions.value.find(
    (opt) => opt.type_code === scheduleType
  );
  return option ? option.type_name : scheduleType;
};

const formatShiftTime = (timeSlotCode) => {
  const timeSlot = timeSlotOptions.value.find(
    (t) => t.slot_code === timeSlotCode
  );
  if (timeSlot) {
    return `${timeSlot.start_time}-${timeSlot.end_time}`;
  }

  // 回退映射
  const timeMap = {};
  return timeMap[timeSlotCode] || timeSlotCode;
};

const getShiftStatusType = (status) => {
  const typeMap = {
    1: "primary", // 正常 → primary
    0: "info", // 取消 → info
    2: "warning", // 调班 → warning
    3: "danger", // 请假 → danger
  };
  return typeMap[status] || "info";
};

const getShiftStatusText = (status) => {
  const textMap = {
    1: "已安排",
    0: "已取消",
    2: "调班中",
    3: "请假中",
  };
  return textMap[status] || status;
};

// 新增：数据库状态映射到 ShiftDetail 组件状态
const mapDbStatusToShiftStatus = (dbStatus) => {
  const statusMap = {
    1: "scheduled", // 正常 → 已安排
    0: "cancelled", // 取消 → 已取消
    2: "scheduled", // 调班 → 已安排（显示调班按钮）
    3: "cancelled", // 请假 → 已取消
  };
  return statusMap[dbStatus] || "scheduled";
};

// 新增：排班类型映射到班次类型
const mapScheduleTypeToShiftType = (scheduleType) => {
  // 来自加载数据映射
  const typeMap = {};
  return typeMap[scheduleType] || "morning";
};

const formatDate = (dateString) => {
  return dateString;
};

const formatSimpleDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const getLunarDate = (date) => {
  const lunarDays = [
    "初一",
    "初二",
    "初三",
    "初四",
    "初五",
    "初六",
    "初七",
    "初八",
    "初九",
    "初十",
    "十一",
    "十二",
    "十三",
    "十四",
    "十五",
    "十六",
    "十七",
    "十八",
    "十九",
    "二十",
    "廿一",
    "廿二",
    "廿三",
    "廿四",
    "廿五",
    "廿六",
    "廿七",
    "廿八",
    "廿九",
    "三十",
  ];
  return lunarDays[date.getDate() % 30];
};

const getWeekday = (dateString) => {
  const date = new Date(dateString);
  return weekdays[date.getDay()];
};

// 获取科室名称（需要根据实际情况实现）
const getDepartmentName = (departmentId) => {
  if (!departmentId) return "未知科室";

  const department = departmentOptions.value.find(
    (dept) => dept.department_id === departmentId
  );

  return department ? department.department_name : `科室${departmentId}`;
};

// 构建查询参数
const buildQueryParams = () => {
  const params = {
    view_type: viewMode.value,
    staff_id: store.state.user?.user_id || null, // 当前登录医生ID
  };

  // 根据视图模式设置日期范围
  if (viewMode.value === "month") {
    const year = currentDate.value.getFullYear();
    const month = currentDate.value.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);

    params.start_date = formatSimpleDate(firstDay);
    params.end_date = formatSimpleDate(lastDay);
  } else if (viewMode.value === "week") {
    const start = new Date(currentDate.value);
    start.setDate(start.getDate() - start.getDay());
    const end = new Date(start);
    end.setDate(end.getDate() + 6);

    params.start_date = formatSimpleDate(start);
    params.end_date = formatSimpleDate(end);
  } else if (viewMode.value === "day") {
    params.date = formatSimpleDate(currentDate.value);
  }

  return params;
};

// 更新概览数据
const updateOverviewData = (data) => {
  const today = formatSimpleDate(new Date());
  const todayShifts = data.filter(
    (item) => item.schedule_date === today
  ).length;

  // 计算本周班次
  const weekStart = new Date();
  weekStart.setDate(weekStart.getDate() - weekStart.getDay());
  const weekEnd = new Date(weekStart);
  weekEnd.setDate(weekEnd.getDate() + 6);

  const weekShifts = data.filter((item) => {
    const itemDate = new Date(item.schedule_date);
    return itemDate >= weekStart && itemDate <= weekEnd;
  }).length;

  // 计算本月工作时长（这里需要根据实际情况计算）
  const monthStart = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth(),
    1
  );
  const monthEnd = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1,
    0
  );

  const monthShifts = data.filter((item) => {
    const itemDate = new Date(item.schedule_date);
    return itemDate >= monthStart && itemDate <= monthEnd;
  });

  // 假设每个班次4小时
  const totalHours = monthShifts.length * 4;

  overview.todayShifts = todayShifts;
  overview.weekShifts = weekShifts;
  overview.totalHours = totalHours;
  // 待处理申请需要从其他接口获取
  overview.pendingRequests = 0;
};

// 加载排班时间选项
const loadTimeSlots = async () => {
  try {
    const res = await getTimeSlotList();
    const payload = res && res.data ? res.data : res;
    if (payload && payload.code === 200 && Array.isArray(payload.data)) {
      timeSlotOptions.value = payload.data;
    } else if (Array.isArray(payload)) {
      timeSlotOptions.value = payload;
    } else {
      console.warn("getTimeSlotList 返回格式异常：", payload);
      // 设置默认值
      timeSlotOptions.value = [
        { slot_code: "morning", start_time: "08:00", end_time: "12:00" },
        { slot_code: "afternoon", start_time: "14:00", end_time: "18:00" },
        { slot_code: "night", start_time: "18:00", end_time: "22:00" },
      ];
    }
  } catch (e) {
    console.error("加载排班时间失败", e);
    ElMessage.error("加载排班时间失败");
  }
};

// 加载排班类型选项
const loadScheduleTypes = async () => {
  try {
    const res = await getScheduleTypeList();
    const payload = res && res.data ? res.data : res;
    if (payload && payload.code === 200 && Array.isArray(payload.data)) {
      scheduleTypeOptions.value = payload.data;
    } else if (Array.isArray(payload)) {
      scheduleTypeOptions.value = payload;
    } else {
      console.warn("getScheduleTypeList 返回格式异常：", payload);
      // 设置默认值
      scheduleTypeOptions.value = [
        { type_code: "normal", type_name: "普通班" },
        { type_code: "emergency", type_name: "急诊班" },
        { type_code: "overtime", type_name: "加班" },
        { type_code: "rest", type_name: "休息" },
      ];
    }
  } catch (e) {
    console.error("加载排班类型失败", e);
    ElMessage.error("加载排班类型失败");
  }
};

// 加载科室列表
const loadDepartments = async () => {
  try {
    const res = await getDepartmentList();
    const payload = res && res.data ? res.data : res;
    if (payload && payload.code === 200 && Array.isArray(payload.data)) {
      departmentOptions.value = payload.data;
    } else if (Array.isArray(payload)) {
      departmentOptions.value = payload;
    } else {
      console.warn("getDepartmentList 返回格式异常：", payload);
      // 设置默认值或保持空数组
      departmentOptions.value = [];
    }
  } catch (e) {
    console.error("加载科室列表失败", e);
    ElMessage.error("加载科室列表失败");
    departmentOptions.value = [];
  }
};

// 加载当前医生排班数据
const loadDoctorSchedule = async () => {
  const params = buildQueryParams();
  loading.value = true;
  try {
    const res = await queryDoctorScheduleInstanceData(params);
    const payload = res && res.data ? res.data : res;
    if (payload && payload.code === 200 && Array.isArray(payload.data)) {
      scheduleData.value = payload.data;
      updateOverviewData(payload.data);
    } else if (Array.isArray(payload)) {
      scheduleData.value = payload;
      updateOverviewData(payload);
    } else {
      console.warn("queryDoctorScheduleInstanceData 返回格式异常：", payload);
      scheduleData.value = [];
      updateOverviewData([]);
    }
  } catch (e) {
    console.error("加载医生排班数据失败", e);
    ElMessage.error("加载医生排班数据失败");
    scheduleData.value = [];
    updateOverviewData([]);
  } finally {
    loading.value = false;
  }
};

// 初始加载数据
const loadAllData = async () => {
  await Promise.all([loadTimeSlots(), loadScheduleTypes(), loadDepartments()]);
};

// 监听视图模式和日期变化
watch([viewMode, currentDate], () => {
  loadDoctorSchedule();
});

// 生命周期
onMounted(() => {
  loadAllData();
  loadDoctorSchedule();
});
</script>

<style lang="scss" scoped>
.doctor-schedule {
  padding: 20px;
  background: #f5f7fa;
  height: 0;
  min-height: 100%;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
  }
}

.schedule-overview {
  margin-bottom: 20px;
}

.overview-card {
  .overview-item {
    display: flex;
    align-items: center;
  }

  .overview-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    font-size: 24px;
    color: white;

    &.today-shifts {
      background: #409eff;
    }
    &.week-shifts {
      background: #67c23a;
    }
    &.pending-requests {
      background: #e6a23c;
    }
    &.total-hours {
      background: #f56c6c;
    }
  }

  .overview-content {
    .overview-value {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .overview-label {
      color: #909399;
      font-size: 14px;
    }
  }
}

.schedule-calendar-card {
  margin-bottom: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.calendar-nav {
  display: flex;
  align-items: center;
  gap: 12px;

  .current-period {
    font-size: 18px;
    font-weight: 600;
    min-width: 200px;
    text-align: center;
  }
}

.calendar-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

// 今天标识样式
.today-badge {
  display: inline-block;
  width: 18px;
  height: 18px;
  background: #f56c6c;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
  margin-left: 4px;
}

// 月视图样式
.month-view {
  .calendar-weekdays {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    border-bottom: 1px solid #ebeef5;
  }

  .weekday-header {
    padding: 12px;
    text-align: center;
    font-weight: 600;
    color: #303133;
    background: #f8f9fa;
  }

  .calendar-days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
  }

  .calendar-day {
    min-height: 120px;
    border: 1px solid #ebeef5;
    padding: 8px;
    background: white;

    &.other-month {
      background: #fafafa;
      color: #c0c4cc;
    }

    &.today {
      background: #f0f9ff;

      .today-badge {
        background: #f56c6c;
      }

      .day-number {
        color: #409eff;
        font-weight: bold;
      }
    }

    &.weekend {
      background: #fef6f6;
    }
  }

  .day-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .day-number-wrapper {
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .day-number {
      font-weight: 600;
      color: #303133;
    }

    .lunar-date {
      font-size: 12px;
      color: #909399;
    }
  }

  .day-shifts {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .shift-item {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    &.morning-shift {
      background: #ecf5ff;
      border-left: 3px solid #409eff;
    }

    &.afternoon-shift {
      background: #f0f9eb;
      border-left: 3px solid #67c23a;
    }

    &.night-shift {
      background: #fdf6ec;
      border-left: 3px solid #e6a23c;
    }

    &.emergency-shift {
      background: #fef0f0;
      border-left: 3px solid #f56c6c;
    }

    .shift-time {
      font-weight: 500;
      margin-bottom: 2px;
    }

    .shift-location {
      color: #606266;
    }
  }
}

// 周视图样式
.week-view {
  .week-header {
    padding: 16px;
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    border-bottom: 1px solid #ebeef5;
  }

  .week-timeline {
    display: flex;
    height: 600px;
    overflow-y: auto;
  }

  .time-slots {
    width: 80px;
    border-right: 1px solid #ebeef5;
  }

  .time-slot {
    height: 60px;
    padding: 8px;
    text-align: right;
    font-size: 12px;
    color: #909399;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
  }

  .week-days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    flex: 1;
  }

  .week-day {
    border-right: 1px solid #ebeef5;

    &.today {
      background: #f0f9ff;

      .day-date {
        color: #409eff;
        font-weight: bold;
      }

      .today-badge {
        background: #f56c6c;
      }
    }

    &.weekend {
      background: #fef6f6;
    }

    &:last-child {
      border-right: none;
    }
  }

  .day-header {
    padding: 12px;
    text-align: center;
    border-bottom: 1px solid #ebeef5;
    background: #f8f9fa;

    .day-name {
      font-weight: 600;
      margin-bottom: 4px;
    }

    .day-date-wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
    }

    .day-date {
      color: #909399;
      font-size: 14px;
    }
  }

  .day-timeline {
    position: relative;
  }

  .timeline-slot {
    height: 60px;
    border-bottom: 1px solid #ebeef5;
    position: relative;
    cursor: pointer;

    &:hover {
      background: #f5f7fa;
    }
  }

  .timeline-shift {
    position: absolute;
    left: 4px;
    right: 4px;
    padding: 8px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }

    &.morning-shift {
      background: #ecf5ff;
      border: 1px solid #409eff;
    }

    &.afternoon-shift {
      background: #f0f9eb;
      border: 1px solid #67c23a;
    }

    &.night-shift {
      background: #fdf6ec;
      border: 1px solid #e6a23c;
    }

    &.emergency-shift {
      background: #fef0f0;
      border: 1px solid #f56c6c;
    }

    .shift-info {
      .shift-time {
        font-weight: 500;
        margin-bottom: 2px;
      }

      .shift-location {
        color: #606266;
      }
    }
  }
}

// 日视图样式
.day-view {
  .day-header {
    padding: 16px;
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    border-bottom: 1px solid #ebeef5;
  }

  .day-timeline {
    display: flex;
    height: 800px;
    overflow-y: auto;
  }

  .time-slots {
    width: 80px;
    border-right: 1px solid #ebeef5;
  }

  .time-slot {
    height: 60px;
    padding: 8px;
    text-align: right;
    font-size: 12px;
    color: #909399;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
  }

  .day-schedule {
    flex: 1;
    position: relative;
  }

  .timeline-slot {
    height: 60px;
    border-bottom: 1px solid #ebeef5;
    position: relative;
    cursor: pointer;

    &:hover {
      background: #f5f7fa;
    }
  }

  .timeline-shift {
    position: absolute;
    left: 4px;
    right: 4px;
    padding: 12px;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    &.morning-shift {
      background: #ecf5ff;
      border: 1px solid #409eff;
    }

    &.afternoon-shift {
      background: #f0f9eb;
      border: 1px solid #67c23a;
    }

    &.night-shift {
      background: #fdf6ec;
      border: 1px solid #e6a23c;
    }

    &.emergency-shift {
      background: #fef0f0;
      border: 1px solid #f56c6c;
    }

    .shift-info {
      .shift-time {
        font-weight: 500;
        margin-bottom: 4px;
      }

      .shift-location {
        color: #606266;
        margin-bottom: 4px;
      }

      .shift-type {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.recent-schedule-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .doctor-schedule {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .calendar-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .calendar-actions {
    width: 100%;
    justify-content: space-between;
  }

  .week-timeline,
  .day-timeline {
    height: 400px;
  }

  // 移动端今天标识调整
  .today-badge {
    width: 16px;
    height: 16px;
    font-size: 10px;
    line-height: 16px;
  }
}
</style>